document.addEventListener('DOMContentLoaded', function() {
    // 轮播图数据
    const slides = [
        {
            image: 'images/banner1.jpg',
            title: '新版本「星火燎原」现已上线',
            description: '探索全新剧情，解锁限定角色'
        },
        {
            image: 'images/banner2.jpg',
            title: '限时活动「星火试炼」',
            description: '参与活动赢取丰厚奖励'
        },
        {
            image: 'images/banner3.jpg',
            title: '新角色「星火」登场',
            description: '掌握星火之力，成为最强战士'
        }
    ];

    let currentSlide = 0;
    const sliderContainer = document.querySelector('.slider-container');
    const dots = document.querySelectorAll('.dot');

    // 初始化轮播图
    function initSlider() {
        // 清空现有内容
        sliderContainer.innerHTML = '';
        
        // 创建新的轮播图内容
        slides.forEach((slide, index) => {
            const slideElement = document.createElement('div');
            slideElement.className = `slide ${index === 0 ? 'active' : ''}`;
            slideElement.innerHTML = `
                <img src="${slide.image}" alt="${slide.title}">
                <div class="slide-content">
                    <h2>${slide.title}</h2>
                    <p>${slide.description}</p>
                    <button class="cta-button">了解更多</button>
                </div>
            `;
            sliderContainer.appendChild(slideElement);
        });
    }

    // 切换轮播图
    function changeSlide(index) {
        const allSlides = document.querySelectorAll('.slide');
        allSlides.forEach(slide => slide.classList.remove('active'));
        dots.forEach(dot => dot.classList.remove('active'));

        allSlides[index].classList.add('active');
        dots[index].classList.add('active');
        currentSlide = index;
    }

    // 自动轮播
    function autoSlide() {
        currentSlide = (currentSlide + 1) % slides.length;
        changeSlide(currentSlide);
    }

    // 点击圆点切换轮播图
    dots.forEach((dot, index) => {
        dot.addEventListener('click', () => {
            changeSlide(index);
        });
    });

    // 初始化轮播图并开始自动播放
    initSlider();
    let slideInterval = setInterval(autoSlide, 5000);

    // 鼠标悬停时暂停自动播放
    const heroSlider = document.querySelector('.hero-slider');
    heroSlider.addEventListener('mouseenter', () => {
        clearInterval(slideInterval);
    });

    heroSlider.addEventListener('mouseleave', () => {
        slideInterval = setInterval(autoSlide, 5000);
    });

    // 用户下拉菜单功能
    const userAvatar = document.querySelector('.user-avatar');
    const userDropdown = document.querySelector('.user-dropdown');

    // 点击头像显示/隐藏下拉菜单
    userAvatar.addEventListener('click', (e) => {
        e.stopPropagation();
        userDropdown.style.display = userDropdown.style.display === 'block' ? 'none' : 'block';
    });

    // 点击页面其他地方关闭下拉菜单
    document.addEventListener('click', () => {
        userDropdown.style.display = 'none';
    });

    // 阻止下拉菜单内部点击事件冒泡
    userDropdown.addEventListener('click', (e) => {
        e.stopPropagation();
    });

    // 退出登录功能
    const logoutBtn = document.querySelector('.logout-btn');
    logoutBtn.addEventListener('click', (e) => {
        e.preventDefault();
        if (confirm('确定要退出登录吗？')) {
            window.location.href = 'login.html';
        }
    });

    // 内容标签切换功能
    const tabs = document.querySelectorAll('.tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            tabs.forEach(t => t.classList.remove('active'));
            tab.classList.add('active');
            // 这里可以添加切换内容的逻辑
        });
    });

    // 搜索框功能
    const searchBox = document.querySelector('.search-box input');
    const searchButton = document.querySelector('.search-box button');

    searchButton.addEventListener('click', () => {
        const searchTerm = searchBox.value.trim();
        if (searchTerm) {
            // 这里可以添加搜索逻辑
            console.log('搜索:', searchTerm);
        }
    });

    searchBox.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            const searchTerm = searchBox.value.trim();
            if (searchTerm) {
                // 这里可以添加搜索逻辑
                console.log('搜索:', searchTerm);
            }
        }
    });

    // 功能导航区悬停效果
    const featureItems = document.querySelectorAll('.feature-item');
    featureItems.forEach(item => {
        item.addEventListener('mouseenter', () => {
            item.style.transform = 'translateY(-5px)';
        });

        item.addEventListener('mouseleave', () => {
            item.style.transform = 'translateY(0)';
        });
    });

    // 内容卡片悬停效果
    const contentCards = document.querySelectorAll('.content-card');
    contentCards.forEach(card => {
        card.addEventListener('mouseenter', () => {
            card.style.transform = 'translateY(-5px)';
        });

        card.addEventListener('mouseleave', () => {
            card.style.transform = 'translateY(0)';
        });
    });

    // 导航栏滚动效果
    let lastScrollTop = 0;
    const navbar = document.querySelector('.navbar');

    window.addEventListener('scroll', () => {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        
        if (scrollTop > lastScrollTop) {
            // 向下滚动
            navbar.style.transform = 'translateY(-100%)';
        } else {
            // 向上滚动
            navbar.style.transform = 'translateY(0)';
        }
        
        lastScrollTop = scrollTop;
    });

    // 模态窗口相关
    const bindGameAccountModal = document.getElementById('bindGameAccountModal');
    const bindGameAccountForm = document.getElementById('bindGameAccountForm');
    const closeModalButtons = document.querySelectorAll('.close-modal');
    const bindGameAccountLinks = document.querySelectorAll('.bind-game-account');

    // 获取当前登录用户ID（从session或localStorage中获取）
    const getCurrentUserId = () => {
        const user = JSON.parse(localStorage.getItem('user') || sessionStorage.getItem('user') || '{}');
        return user.id || user.userId || 'U000000001'; // 使用数据库中存在的用户ID
    };

    // 显示提示信息
    function showMessage(message, isError = false) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${isError ? 'error' : 'success'}`;
        messageDiv.textContent = message;
        document.body.appendChild(messageDiv);
        
        setTimeout(() => {
            messageDiv.remove();
        }, 3000);
    }

    // 打开绑定游戏账号模态窗口
    function openBindGameAccountModal() {
        bindGameAccountModal.style.display = 'flex';
    }

    // 关闭模态窗口
    function closeModal() {
        bindGameAccountModal.style.display = 'none';
    }

    // 为所有关闭按钮添加点击事件
    closeModalButtons.forEach(button => {
        button.addEventListener('click', closeModal);
    });

    // 点击模态窗口外部关闭
    window.addEventListener('click', (event) => {
        if (event.target === bindGameAccountModal) {
            closeModal();
        }
    });

    // 处理绑定游戏账号表单提交
    bindGameAccountForm.addEventListener('submit', async (event) => {
        event.preventDefault();
        const gameUid = document.getElementById('gameUid').value;
        const userId = getCurrentUserId();
        
        if (!userId) {
            showMessage('请先登录', true);
            return;
        }
        
        try {
            const response = await fetch(`http://localhost:8080/userapi/users/profile/${userId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    gameUid: gameUid
                })
            });
            
            const result = await response.json();
            
            if (response.ok) {
                showMessage('游戏账号绑定成功');
                closeModal();
                // 刷新用户信息显示
                loadUserProfile();
            } else {
                showMessage(result.message || '绑定失败', true);
            }
        } catch (error) {
            console.error('绑定游戏账号失败:', error);
            showMessage('绑定游戏账号失败，请稍后重试', true);
        }
    });

    // 为所有绑定游戏账号链接添加点击事件
    bindGameAccountLinks.forEach(link => {
        link.addEventListener('click', (event) => {
            event.preventDefault();
            openBindGameAccountModal();
        });
    });

    // 页面加载时获取用户信息
    async function loadUserProfile() {
        const user = JSON.parse(localStorage.getItem('user') || sessionStorage.getItem('user') || '{}');
        const userId = user.userId;
        if (!userId) return;

        try {
            const response = await fetch(`http://localhost:8080/userapi/users/profile/${userId}`);
            if (response.ok) {
                const result = await response.json();
                const userData = result.user || result;

                // 更新头像
                document.querySelectorAll('.user-avatar img').forEach(img => {
                    img.src = userData.avatar || 'images/default-avatar.png';
                });
                // 更新用户名
                document.querySelectorAll('.user-info h4').forEach(h4 => {
                    h4.textContent = userData.nickname || '用户名';
                });
                // 更新UID
                document.querySelectorAll('.user-info p').forEach(p => {
                    p.textContent = `UID: ${userData.gameUid || '未绑定'}`;
                });
            }
        } catch (error) {
            console.error('加载用户信息失败:', error);
        }
    }

    // 页面加载时获取用户信息
    loadUserProfile();

    // 检查登录状态
    function checkLoginStatus() {
        const token = localStorage.getItem('token') || sessionStorage.getItem('token');
        const user = JSON.parse(localStorage.getItem('user') || sessionStorage.getItem('user') || '{}');
        
        console.log('=== Home页面登录状态检查 ===');
        console.log('Token存在:', !!token);
        console.log('用户信息:', user);
        
        if (token) {
            console.log('Token内容:', token.substring(0, 50) + '...');
        }
        
        return { token, user };
    }
    
    // 页面加载时检查登录状态
    const loginStatus = checkLoginStatus();
    
    // 如果用户已登录，更新用户信息显示
    if (loginStatus.user && loginStatus.user.nickname) {
        document.querySelectorAll('.user-info h4').forEach(el => {
            el.textContent = loginStatus.user.nickname;
        });
        
        if (loginStatus.user.avatar) {
            document.querySelectorAll('.user-avatar img').forEach(img => {
                img.src = loginStatus.user.avatar;
            });
        }
    }
}); 